package com.atguigu.java.ai.langchain4j.config;

import com.atguigu.java.ai.langchain4j.store.XiaozhiMongoChatMemoryStore;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.List;

@Configuration
public class XiaoZhimessageChatMemoryProviderConfig {
    @Autowired
    private EmbeddingModel embeddingModel;
    @Autowired
    private EmbeddingStore<TextSegment> embeddingStore;
    @Autowired
    private XiaozhiMongoChatMemoryStore xiaozhiMongoChatMemoryStore;
    @Bean
    public ChatMemoryProvider XZmessageChatMemoryProvider(){

        ChatMemoryProvider chatMemoryProvider = new ChatMemoryProvider(){
            @Override
            public ChatMemory get(Object memoryId) {
                MessageWindowChatMemory memory = MessageWindowChatMemory.builder()
                        .id(memoryId)
                        .chatMemoryStore(xiaozhiMongoChatMemoryStore)
                        .maxMessages(10)
                        .build();
                return memory;
            }
        };
        return chatMemoryProvider;
    }
    @Bean
    ContentRetriever contentRetrieverXiaozhi(){
        List<Document> documents = FileSystemDocumentLoader.loadDocuments("D:\\0725\\笔记\\小智医疗项目\\小智医疗项目-xu\\资料\\04-科室信息");
        // 初始化向量存储内存
        InMemoryEmbeddingStore<TextSegment> inMemoryEmbeddingStore = new InMemoryEmbeddingStore<>();

        // 向量转化
        EmbeddingStoreIngestor.ingest(documents, inMemoryEmbeddingStore);

        return EmbeddingStoreContentRetriever.from(inMemoryEmbeddingStore);

    }
    @Bean
    ContentRetriever contentRetrieverXiaozhiPincone() {
        // 创建一个 EmbeddingStoreContentRetriever 对象，用于从嵌入存储中检索内容
        return EmbeddingStoreContentRetriever
                .builder()
                // 设置用于生成嵌入向量的嵌入模型
                .embeddingModel(embeddingModel)
                // 指定要使用的嵌入存储
                .embeddingStore(embeddingStore)
                // 设置最大检索结果数量，这里表示最多返回 1 条匹配结果
                .maxResults(1)
                // 设置最小得分阈值，只有得分大于等于 0.8 的结果才会被返回
                .minScore(0.8)
                // 构建最终的 EmbeddingStoreContentRetriever 实例
                .build();
    }
}
